package com.dir.net.controller;

import com.dir.net.pojo.NetworkCard;
import com.dir.net.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("")
@Api(tags = "网络数据接口")
public class NetController {
    @Autowired
    private PacketCapture packetCapture;

    private final NetworkInterface[] deviceList = JpcapCaptor.getDeviceList();

    private Thread run;

    @GetMapping("/cards")
    @ApiOperation("查看所有的网卡信息")
    public Result<List<NetworkCard>> getCards() {
        List<NetworkCard> data = new ArrayList<>();
        for (int i = 0; i < deviceList.length; i++) {
            NetworkInterface device = deviceList[i];
            String loopback = device.loopback ? "true" : "false";

            String macAddress = "";
            for(byte b : device.mac_address) {
                macAddress += Integer.toHexString(b & 0xff);
            }

            String addr_ipv4 = "未设置";
            String subnet_ipv4= "未设置";
            String broadcast_ipv4= "未设置";

            String addr_ipv6= "未设置";
            String subnet_ipv6= "未设置";
            String broadcast_ipv6= "未设置";

            for(NetworkInterfaceAddress a: device.addresses) {
                String address = "" + a.address;
                String subnet = "" + a.subnet;
                String broadcast = "" + a.broadcast;
                if(address.contains(":")) {
                    addr_ipv6 = address.substring(1);
                    subnet_ipv6 = subnet.equals("null") ? "未设置" : subnet.substring(1);
                    broadcast_ipv6 = broadcast.equals("null") ? "未设置" : broadcast.substring(1);
                    System.out.println(subnet);
                } else if(address.contains(".")) {
                    addr_ipv4 = address.substring(1);
                    subnet_ipv4 = subnet.equals("null") ? "未设置" : subnet.substring(1);
                    broadcast_ipv4 = broadcast.equals("null") ? "未设置" : broadcast.substring(1);
                }
            }

            data.add(new NetworkCard((long) i,
                    device.description,
                    device.name,
                    device.datalink_description,
                    device.datalink_name,
                    macAddress,
                    loopback,
                    addr_ipv4,
                    subnet_ipv4,
                    broadcast_ipv4,
                    addr_ipv6,
                    subnet_ipv6,
                    broadcast_ipv6
            ));
        }

        return Result.success(data);
    }

    @GetMapping("/listen")
    @ApiOperation("开始抓包")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "protocol", value = "需要是 [\"全部\", \"TCP\", \"UDP\", \"ICMP\", \"ARP\", \"IP\", \"其他\"] 中的一个字符串")
    })
    public Result<String> startListen(@RequestParam Long id,
                                      @RequestParam String protocol,
                                      @RequestParam String sourceIp,
                                      @RequestParam String destIp,
                                      @RequestParam String keyword) {
        Map<String, String> filter = new HashMap<>();
        if (!protocol.isEmpty()) {
            filter.put("协议类型", protocol);
        }
        if (!sourceIp.isEmpty()) {
            filter.put("源IP", sourceIp);
        }
        if (!destIp.isEmpty()) {
            filter.put("目的IP", destIp);
        }
        if (!keyword.isEmpty()) {
            filter.put("keyword", keyword);
        }
        if (run != null && run.getState() != Thread.State.TERMINATED) {
            run.stop();
        }
        packetCapture.clearList();
        packetCapture.setFilter(filter);
        packetCapture.setDevice(deviceList[Math.toIntExact(id)]);
        run = new Thread(packetCapture);
        run.start();
        return Result.success();
    }

    @GetMapping("/stop")
    @ApiOperation("停止抓包")
    public Result<String> stopListen() {
        if (run != null && run.getState() != Thread.State.TERMINATED) {
            run.stop();
        }
        packetCapture.clearList();
        return Result.success();
    }


    @GetMapping("/packets")
    @ApiOperation("返回抓包信息")
    public Result<ArrayList<Map<String, String>>> getPackets() {
        ArrayList<Map<String, String>> packetsDetails = packetCapture.getPacketsDetails();
        return Result.success(packetsDetails);
    }

    @GetMapping("/overview")
    @ApiOperation("返回抓包概况")
    public Result<Map<String, String>> getOverview() {
        return Result.success(PacketAnalyze.getCountMessage());
    }
}
